package com.hand.wfive.base;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.hand.wfive.R;

import java.util.ArrayList;
import java.util.Arrays;

public abstract class BasePopWindow<T extends ViewDataBinding> extends PopupWindow {
    public View contentView;
    public T mBinding;
    public boolean mShowPopCenter;
    protected Context context;
    private ArrayList<Integer> mOnClickViewsId;
    private View.OnClickListener onChildClickListener;
    private boolean fullScreenMode;

    public BasePopWindow(Context context) {
        super(context);
        this.context = context;
        initView();
    }

    protected void debug(String msg) {
        Log.d("testZ", msg);
    }

    /**
     * 获取视图的实际高度.
     */
    protected int getContentViewHeight() {
        View contentView = getContentView();
        int measuredHeight = contentView.getMeasuredHeight();
        if (measuredHeight <= 0) {
            contentView.measure(0, 0);
            measuredHeight = contentView.getMeasuredHeight();
        }
        return measuredHeight;
    }

    /**
     * 获取视图的实际宽度.
     */
    protected int getContentViewWidth() {
        View contentView = getContentView();
        int measuredWidth = contentView.getMeasuredWidth();
        if (measuredWidth <= 0) {
            contentView.measure(0, 0);
            measuredWidth = contentView.getMeasuredWidth();
        }
        return measuredWidth;
    }

    protected abstract int getLayoutId();

    protected int getDarkViewId() {
        return 0;
    }

    public void setFullScreen() {
        fullScreenMode = true;
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
    }

    public void setNoScreen() {
        fullScreenMode = true;
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    public void setWrapScreen() {
        fullScreenMode = false;
        setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    protected void initView() {
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(context), getLayoutId(), null, false);
        contentView = mBinding.getRoot();
//        contentView = LayoutInflater.from(context).inflate(getLayoutId(), null);
        setContentView(contentView);

        // 点击外部可消失
        setFocusable(true);

        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        ColorDrawable dw = new ColorDrawable(context.getResources().getColor(R.color.trans70));
        setBackgroundDrawable(dw);
        initAnimStyle(context);
        View vHide = contentView.findViewById(getDarkViewId());
        if (vHide != null) {
            vHide.setOnClickListener(v -> dismiss());
        }
        setNoScreen();
    }


    protected void initAnimStyle(Context context) {

    }

    /**
     * 下拉动画方法，子类自行调用
     *
     * @param context
     * @param view
     */
    protected void setAnimStyleDown(Context context, View view) {
//        setAnimationStyle(R.style.popupAnimation);
        Animation loadAnimation = AnimationUtils.loadAnimation(context,
                R.anim.short_menu_pop_in);
        loadAnimation.setFillAfter(true);
        view.startAnimation(loadAnimation);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        debug("xoff=" + xoff);
        debug("yoff=" + yoff);
        super.showAsDropDown(anchor, xoff, yoff);
    }

    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT >= 24 && anchor != null && fullScreenMode) {
            Rect rect = new Rect();
            anchor.getWindowVisibleDisplayFrame(rect);
            Activity activity = (Activity) anchor.getContext();
            Rect outRect1 = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
            int h = outRect1.height() - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
       /* if (Build.VERSION.SDK_INT >= 24 && anchor != null && fullScreenMode) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);*/
    }

    public void showAtAnchorBottom(View parent) {
        super.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    public void showAsDropDownAlignRight(View anchor) {
        View contentView = getContentView();
        contentView.measure(0, 0);
        int width2 = contentView.getMeasuredWidth();

        int width1 = anchor.getMeasuredWidth();

        int xoff = width1 - width2;
        int yoff = 0;

        showAsDropDown(anchor, xoff, yoff);
    }

    /**
     * 指定在anchorYDown的下方，左对齐anchorXLeft，并且设置popwindow的宽度width.
     */
    public void showAsDropDownAlignXY(View anchorYDown, View anchorXLeft, int width) {
        setWidth(width);

        int[] location = new int[2];
        anchorXLeft.getLocationInWindow(location);

        int[] location2 = new int[2];
        anchorYDown.getLocationInWindow(location2);

        int xoff = location[0] - location2[0];
        showAsDropDown(anchorYDown, xoff, 0);
    }

    public void showAsDropDownByWidth(View anchor, int width) {
        setWidth(width);
        showAsDropDown(anchor);
    }

    public void showAsDropDownInCenter(View anchor) {
        showAsDropDownInCenterFixWidth(anchor, null);
    }

    public void showAsDropDownInCenterFixWidth(View anchor, Integer fixWidth) {
        if (fixWidth != null) {
            setWidth(fixWidth);
        }

        int x1 = 0;
        if (fixWidth != null) {
            x1 = fixWidth;
        } else {
            View contentView = getContentView();
            contentView.measure(0, 0);
            x1 = contentView.getMeasuredWidth();
        }
        debug("x1=" + x1);

        int x = anchor.getMeasuredWidth();
        debug("x=" + x);

        int xoff = (x - x1) / 2;
        int yoff = 0;

        showAsDropDown(anchor, xoff, yoff);
    }

    public void showAsDropDownSameWidth(View anchor) {
        int width = anchor.getMeasuredWidth();
        debug("anchor width = " + width);
        showAsDropDownByWidth(anchor, width);
    }

    /**
     * 显示在右上角.右边对齐.
     */
    public void showAsUpRight(View anchor) {
        int w1 = anchor.getMeasuredWidth();
        int w2 = getContentViewWidth();
        int xoff = w1 - w2;
        debug("w1=" + w1);
        debug("w2=" + w2);
        debug("xoff=" + xoff);

        int h2 = getContentViewHeight();
        int h1 = anchor.getMeasuredHeight();
        int yoff = -(h1 + h2);
        debug("h1=" + h1);
        debug("h2=" + h2);
        debug("yoff=" + yoff);
        showAsDropDown(anchor, xoff, yoff);
    }

    public void showAsDownCenter(View anchor) {
        int w1 = anchor.getMeasuredWidth();
        int w2 = getContentViewWidth();
        int xoff = w1 / 2 - w2;
        debug("w1=" + w1);
        debug("w2=" + w2);
        debug("xoff=" + xoff);
        showAsDropDown(anchor, xoff, 0);
    }

    public void showAsUpRightCenter(View anchor) {
        showAsUpRightCenter(anchor, 0);
    }

    public void showAsUpRightCenter(View anchor, int yoffAdd) {
        int w1 = anchor.getMeasuredWidth() / 2;
        int w2 = getContentViewWidth();
        int xoff = w1 - w2;
        debug("w1=" + w1);
        debug("w2=" + w2);
        debug("xoff=" + xoff);

        int h2 = getContentViewHeight();
        int h1 = anchor.getMeasuredHeight();
        int yoff = -(h1 + h2);
        debug("h1=" + h1);
        debug("h2=" + h2);
        debug("yoff=" + yoff);
        showAsDropDown(anchor, xoff, yoff + yoffAdd);
    }

    public void backgroundAlpha(float bgAlpha) {
        if (context instanceof Activity) {
            Window window = ((Activity) context).getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.alpha = bgAlpha; //0.0-1.0
            window.setAttributes(lp);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (mShowPopCenter) {
            backgroundAlpha(1f);
        }
    }

    public void addOnChildClickViews(Integer... onClickViewsId) {
        if (mOnClickViewsId == null) {
            mOnClickViewsId = new ArrayList<>();
        }
        this.mOnClickViewsId.addAll(Arrays.asList(onClickViewsId));
    }

    public void setOnChildClickListener(View.OnClickListener onClickListener) {
        this.onChildClickListener = onClickListener;
        for (int id : mOnClickViewsId) {
            View view = contentView.findViewById(id);
            view.setOnClickListener(onChildClickListener);
        }
    }

}
